<!--
# coding=UTF-8
# Copyright (c) 2025 Bird Software Solutions Ltd
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License 2.0
# which accompanies this distribution, and is available at
# https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#    Neil Mackenzie - initial API and implementation
#    Benjamin Arfa - improvements
#
-->
{% extends 'base.html' %}

{% block content %}
<div class="container">
    <h1 class="page-title">Duplicate Primary Members</h1>

    <a href="{% url 'pybirdai:workflow_task' task_number=2 operation='review' %}">Back to Review</a>
    <!-- Add filter form -->
    <div class="filter-container">
        <form method="get" class="filter-form">
            <div class="filter-group">
                <label for="foreign_cube">Foreign Cube:</label>
                <select name="foreign_cube" id="foreign_cube">
                    <option value="">All Foreign Cubes</option>
                    {% for cube in foreign_cubes %}
                        <option value="{{ cube }}" {% if request.GET.foreign_cube == cube %}selected{% endif %}>
                            {{ cube }}
                        </option>
                    {% endfor %}
                </select>
            </div>
            <div class="filter-group">
                <label for="primary_cube">Primary Cube:</label>
                <select name="primary_cube" id="primary_cube">
                    <option value="">All Primary Cubes</option>
                    {% for cube in primary_cubes %}
                        <option value="{{ cube }}" {% if request.GET.primary_cube == cube %}selected{% endif %}>
                            {{ cube }}
                        </option>
                    {% endfor %}
                </select>
            </div>
            <button type="submit" class="filter-button">Apply Filter</button>
            <a href="{% url 'pybirdai:duplicate_primary_member_id_list' %}" class="clear-button">Clear Filters</a>
        </form>
    </div>

    <div class="table-container">
        {# Wrap the table in a form for bulk delete #}
        {# NOTE: The action URL needs to be defined in your urls.py and handled by a view #}
        {# that processes bulk deletion. This view should then redirect back to this page #}
        {# without filters to fulfill the "clicking delete resets the filters" requirement. #}
        <form method="POST" action="{% url 'pybirdai:bulk_delete_cube_structure_item_links' %}?page={{ page_obj.paginator.num_pages }}{% if request.GET.foreign_cube %}&foreign_cube={{ request.GET.foreign_cube }}{% endif %}{% if request.GET.primary_cube %}&primary_cube={{ request.GET.primary_cube }}{% endif %}" id="bulk-delete-form">
            {% csrf_token %}
            {# Add a bulk delete button #}
            <div class="bulk-actions">
                 {# Button is disabled by default and enabled by JavaScript when items are selected #}
                <button type="submit" class="delete-button" id="bulk-delete-button" disabled>Delete Selected</button>
            </div>
            <table>
                <thead>
                    <tr>
                        {# Add a column for checkboxes #}
                        <th><input type="checkbox" id="select-all"></th>
                        <th>Foreign Cube</th>
                        <th>Join Identifier</th>
                        <th>Foreign Variable</th>
                        <th>Primary Cube</th>
                        <th>Primary Variable</th>
                        <th>Cube Link ID</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for link in duplicate_links %}
                    <tr>
                        {# Add a checkbox for each item #}
                        <td><input type="checkbox" name="selected_items" value="{{ link.cube_structure_item_link_id }}"></td>
                        <td>{{ link.cube_link_id.foreign_cube_id.cube_id }}</td>
                        <td>{{ link.cube_link_id.join_identifier }}</td>
                        <td>{{ link.foreign_cube_variable_code.variable_id.variable_id }}</td>
                        <td>{{ link.cube_link_id.primary_cube_id.cube_id }}</td>
                        <td>{{ link.primary_cube_variable_code.variable_id.variable_id }}</td>
                        <td>{{ link.cube_link_id.cube_link_id }}</td>
                        <td>
                            {# Keep individual delete form - relies on its view redirecting to reset filters #}
                            <form method="POST" action="{% url 'pybirdai:delete_cube_structure_item_link_dupl' link.cube_structure_item_link_id %}"
                                  onsubmit="return confirm('Are you sure you want to delete these links?');"
                                  style="display: inline;">
                                {% csrf_token %}
                                <button type="submit" class="delete-button">Delete</button>
                            </form>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>


        </form>
    </div>

    {% if is_paginated %}
    <div class="pagination">
        <span class="step-links">
            {% if page_obj.has_previous %}
                {# Modify pagination links to reset filters by pointing to the base URL + page #}
                <a href="{% url 'pybirdai:duplicate_primary_member_id_list' %}?page=1{% if request.GET.foreign_cube %}&foreign_cube={{ request.GET.foreign_cube }}{% endif %}{% if request.GET.primary_cube %}&primary_cube={{ request.GET.primary_cube }}{% endif %}" class="page-link">&laquo; first</a>
                <a href="{% url 'pybirdai:duplicate_primary_member_id_list' %}?page={{ page_obj.previous_page_number }}{% if request.GET.foreign_cube %}&foreign_cube={{ request.GET.foreign_cube }}{% endif %}{% if request.GET.primary_cube %}&primary_cube={{ request.GET.primary_cube }}{% endif %}" class="page-link">previous</a>
            {% endif %}

            <span class="current-page">
                Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
            </span>

            {% if page_obj.has_next %}
                {# Modify pagination links to keep filters #}
                <a href="{% url 'pybirdai:duplicate_primary_member_id_list' %}?page={{ page_obj.next_page_number }}{% if request.GET.foreign_cube %}&foreign_cube={{ request.GET.foreign_cube }}{% endif %}{% if request.GET.primary_cube %}&primary_cube={{ request.GET.primary_cube }}{% endif %}" class="page-link">next</a>
                <a href="{% url 'pybirdai:duplicate_primary_member_id_list' %}?page={{ page_obj.paginator.num_pages }}{% if request.GET.foreign_cube %}&foreign_cube={{ request.GET.foreign_cube }}{% endif %}{% if request.GET.primary_cube %}&primary_cube={{ request.GET.primary_cube }}{% endif %}" class="page-link">last &raquo;</a>
            {% endif %}
        </span>
    </div>
    {% endif %}
</div>

{# Add JavaScript for select all functionality #}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all');
    const itemCheckboxes = document.querySelectorAll('input[name="selected_items"]');
    const bulkDeleteButton = document.getElementById('bulk-delete-button');
    const bulkDeleteForm = document.getElementById('bulk-delete-form');

    // Function to update the state of the bulk delete button
    function updateButtonState() {
        const checkedCount = document.querySelectorAll('input[name="selected_items"]:checked').length;
        bulkDeleteButton.disabled = checkedCount === 0;
        bulkDeleteButton.textContent = checkedCount > 0 ? `Delete Selected (${checkedCount})` : 'Delete Selected';
    }

    // Event listener for the "Select All" checkbox
    selectAllCheckbox.addEventListener('change', function() {
        itemCheckboxes.forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
        updateButtonState(); // Update button state after changing checkboxes
    });

    // Event listeners for individual item checkboxes
    itemCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            // If an item is unchecked, uncheck the "Select All" checkbox
            if (!this.checked) {
                selectAllCheckbox.checked = false;
            } else {
                 // Optional: Check if all items are checked, and if so, check "Select All"
                 const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                 selectAllCheckbox.checked = allChecked;
            }
            updateButtonState(); // Update button state after changing a checkbox
        });
    });

    // Initial update of the button state on page load
    updateButtonState();

    // Add confirmation message for the bulk delete form
    bulkDeleteForm.addEventListener('submit', function(event) {
        const checkedCount = document.querySelectorAll('input[name="selected_items"]:checked').length;
        if (checkedCount === 0) {
            // This should not happen if the button is disabled, but good as a fallback
            alert('Please select at least one item to delete.');
            event.preventDefault(); // Prevent form submission if no items are selected
        } else {
            const confirmation = confirm(`Are you sure you want to delete ${checkedCount} selected items?`);
            if (!confirmation) {
                event.preventDefault(); // Prevent form submission if user cancels
            }
        }
    });
});
</script>

<style>
    .container {
        padding: 20px;
        width: 95%; /* Changed from max-width */
        margin: 0 auto;
    }

    .page-title {
        color: #2c3e50;
        margin-bottom: 30px;
        padding-bottom: 10px;
        border-bottom: 2px solid #eee;
    }

    .table-container {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        overflow-x: auto;
        margin-bottom: 20px;
    }

    table {
        border-collapse: collapse;
        width: 100%;
        min-width: 800px;
        background-color: white;
    }

    th, td {
        padding: 12px 15px;
        text-align: left;
        border-bottom: 1px solid #e1e1e1;
    }

    th {
        background-color: #f8f9fa;
        color: #2c3e50;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.9em;
        letter-spacing: 0.5px;
    }

    tr:hover {
        background-color: #f5f8fa;
    }

    tr:last-child td {
        border-bottom: none;
    }

    /* Pagination styles */
    .pagination {
        margin-top: 20px;
        text-align: center;
    }

    .step-links {
        display: inline-block;
        padding: 10px;
        background: white;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .page-link {
        display: inline-block;
        padding: 8px 12px;
        margin: 0 4px;
        color: #2c3e50;
        text-decoration: none;
        border-radius: 4px;
    }

    .page-link:hover {
        background-color: #f5f8fa;
    }

    .current-page {
        display: inline-block;
        padding: 8px 12px;
        margin: 0 4px;
        background-color: #f8f9fa;
        color: #2c3e50;
        border-radius: 4px;
    }

    /* Responsive design */
    @media (max-width: 768px) {
        .container {
            padding: 10px;
            width: 98%; /* Adjusted for smaller screens */
        }

        .page-title {
            font-size: 1.5em;
        }

        th, td {
            padding: 8px 10px;
        }
    }

    /* Zebra striping */
    tbody tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    /* Optional: Add some spacing between columns */
    td:not(:last-child), th:not(:last-child) {
        border-right: 1px solid #e1e1e1;
    }

    /* Filter styles */
    .filter-container {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }

    .filter-form {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: flex-end;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 5px;
    }

    .filter-group label {
        font-weight: 600;
        color: #2c3e50;
    }

    .filter-group input {
        padding: 8px;
        border: 1px solid #e1e1e1;
        border-radius: 4px;
        width: 200px;
    }

    .filter-button, .clear-button {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-weight: 600;
        height: 35px;
    }

    .filter-button {
        background-color: #3498db;
        color: white;
    }

    .clear-button {
        background-color: #e1e1e1;
        color: #2c3e50;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .filter-button:hover {
        background-color: #2980b9;
    }

    .clear-button:hover {
        background-color: #d1d1d1;
    }

    .filter-group select {
        padding: 8px;
        border: 1px solid #e1e1e1;
        border-radius: 4px;
        width: 200px;
        background-color: white;
        font-size: 14px;
    }

    .filter-group select:focus {
        outline: none;
        border-color: #3498db;
        box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
    }

    .delete-button {
        background-color: #e74c3c;
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.2s;
    }

    .delete-button:hover {
        background-color: #c0392b;
    }

    /* Styles for checkbox column and bulk actions */
    table th:first-child,
    table td:first-child {
        width: 30px; /* Adjust width as needed */
        text-align: center;
    }

    .bulk-actions {
        margin-top: 15px;
        text-align: right; /* Align button to the right */
    }
</style>
{% endblock %}
